// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:common/image/image_tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:miaowu/app/module/world/audio/recorder/recorder_manager.dart';

import 'water_button.dart';
import 'waveforms_widget.dart';
import 'world_audio_publish_logic.dart';
import 'world_audio_publish_state.dart';

/// @description:
/// @author
/// @date: 2025-01-20 09:58:27
class WorldAudioPublishPage extends StatefulWidget {
  const WorldAudioPublishPage({Key? key, required this.onCallBack}) : super(key: key);

  final Function onCallBack;
  @override
  State<WorldAudioPublishPage> createState() => _WorldAudioPublishPageState();
}

class _WorldAudioPublishPageState extends State<WorldAudioPublishPage> {
  final WorldAudioPublishLogic logic = Get.put(WorldAudioPublishLogic());

  final WorldAudioPublishState state = Get.find<WorldAudioPublishLogic>().state;

  late final RecorderController recorderController;

  String? audioPath;
  bool isRecording = false;
  int audioDuration = 0;
  AudioCardState audioCardState = AudioCardState.initial;

  @override
  void initState() {
    super.initState();
    // _getDir();
    PermissionUtils.microphone();
    RecorderManager.instance.configRecordParams(minTime: 6, maxTime: 10);
    recorderController = RecorderManager.instance.init();
    RecorderManager.instance.onChangeState = (AudioCardState state, int duration, String fildPath) {
      setState(() {
        audioCardState = state;
        if (state == AudioCardState.recording) {
          isRecording = true;
        } else if (state == AudioCardState.initial) {
          isRecording = false;
          audioPath = null;
        } else if (state == AudioCardState.recordingCompleted) {
          isRecording = false;
          audioPath = fildPath;
        }
      });
    };
    RecorderManager.instance.onCurrentDuration = (int duration) {
      setState(() {
        audioDuration = duration;
      });
    };
  }

  @override
  void dispose() {
    RecorderManager.instance.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        clipBehavior: Clip.hardEdge,
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
          color: Colors.white,
        ),
        padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).padding.bottom == 0 ? 10 : (MediaQuery.of(context).padding.bottom - 10)),
        child: Stack(
          children: [
            SizedBox(
                width: double.infinity,
                child: Image.asset('assets/app/images/world/world_top_bg.png', fit: BoxFit.cover)),
            Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Container(
                  margin: const EdgeInsets.only(bottom: 80),
                  child: isRecording == false
                      ? (audioPath == null
                          ? Image.asset('assets/app/images/world/audio_waveform_ing_2.png', width: 186.w)
                          : WaveformsWidget(audioPath: audioPath ?? ''))
                      : AudioWaveforms(
                          enableGesture: true,
                          size: Size(MediaQuery.of(context).size.width / 3 * 2, 100),
                          recorderController: recorderController,
                          waveStyle:
                              const WaveStyle(waveColor: Color(0xFF25D4D0), extendWaveform: true, showMiddleLine: true),
                          decoration:
                              BoxDecoration(borderRadius: BorderRadius.circular(12.0), color: Colors.transparent),
                          padding: const EdgeInsets.only(left: 18),
                          margin: const EdgeInsets.symmetric(horizontal: 15),
                        ),
                ),
                SizedBox(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      if (isRecording == false && audioPath != null)
                        GestureDetector(
                          onTap: () {
                            RecorderManager.instance.deleteAudioFile(
                                audioPath: audioPath ?? '',
                                successCallback: () {
                                  setState(() {
                                    audioPath = null;
                                    audioCardState = AudioCardState.initial;
                                    isRecording = false;
                                  });
                                });
                          },
                          child: Container(
                            margin: const EdgeInsets.only(left: 10),
                            child: Column(
                              children: [
                                Image.asset('assets/app/images/world/audio_del_icon.png', width: 36.w),
                                const SizedBox(height: 3),
                                Text('删除', style: TextStyle(color: Colors.black, fontSize: 13.sp))
                              ],
                            ),
                          ),
                        ),
                      GestureDetector(
                        onTap: () {
                          RecorderManager.instance.startOrStopRecording();
                        },
                        child: Container(
                            padding: const EdgeInsets.only(bottom: 50),
                            child: Stack(
                              children: [
                                Container(
                                    width: 100,
                                    height: 100,
                                    color: Colors.transparent,
                                    child: isRecording
                                        ? ACEWaterButton(color: const Color(0xFF25D4D0).withOpacity(0.2))
                                        : const SizedBox()),
                                Positioned.fill(
                                  child: Center(
                                    child: Image.asset(
                                        isRecording
                                            ? 'assets/app/images/world/audio_start_ing_icon.png'
                                            : 'assets/app/images/world/audio_start_icon.png',
                                        width: 80.w),
                                  ),
                                ),
                                if (isRecording)
                                  Positioned.fill(
                                      top: 35.h,
                                      child: Center(
                                          child: Text(
                                        '${audioDuration}s',
                                        style: TextStyle(
                                            color: Colors.white, fontSize: 13.sp, fontWeight: FontWeight.bold),
                                      ))),
                              ],
                            )),
                      ),
                      if (isRecording == false && audioPath != null)
                        GestureDetector(
                          onTap: () {
                            widget.onCallBack(audioPath);
                            Get.back();
                          },
                          child: Container(
                              margin: const EdgeInsets.only(right: 10),
                              child: Column(
                                children: [
                                  Image.asset('assets/app/images/world/audio_finish_icon.png', width: 36.w),
                                  const SizedBox(height: 3),
                                  Text('完成', style: TextStyle(color: Colors.black, fontSize: 13.sp))
                                ],
                              )),
                        ),
                    ],
                  ),
                ),
                // const SizedBox(height: 30)
              ],
            ),
            Container(
              height: 45,
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              margin: EdgeInsets.symmetric(vertical: 6.w),
              child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                GestureDetector(
                    onTap: () {
                      Get.back();
                    },
                    child: Image.asset('assets/app/images/world/audio_close_icon.png', width: 16.w)),
                Text('录制声音', style: TextStyle(color: Colors.black, fontSize: 17.sp, fontWeight: FontWeight.w500)),
                SizedBox(width: 16.w),
              ]),
            )
          ],
        ),
      ),
    );
  }
}
